<template>
  <div class="content-wrap content-container" v-loading="loading">
    <!-- 搜索区域 -->
    <el-form class="search-wrap" v-model="searchFormData">
      <el-form-item
        class="search-wrap-item"
        label="标题关键字："
        prop="projectTitle"
      >
        <el-input
          width="160px"
          placeholder="请输入标题关键字"
          v-model="searchFormData.projectTitle"
          clearable
          @keyup.enter="getAllReviewRequirement"
        ></el-input>
      </el-form-item>
      <el-form-item class="search-wrap-item" label="时间：" prop="time">
        <el-date-picker
          style="width: 240px"
          type="daterange"
          unlink-panels
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :value-on-clear="null"
          v-model="searchFormData.time"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
          @change="getAllReviewRequirement"
        />
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="primary" @click="createRequirementClick"
          >创建需求</el-button
        >
      </el-form-item> -->
    </el-form>

    <!-- 待审核需求列表 -->
    <div class="card-wrap-table">
      <el-table :data="allReviewRequirement" border style="width: 100%;height: 100%;">
        <el-table-column
          fixed
          type="index"
          label="序号"
          width="60"
          align="center"
        ></el-table-column>
        <el-table-column label="创建人" prop="requirementCreateName" width="120" align="center">
          <template #="{ row }">
            <span>{{ row.requirementCreateName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="需求名称" prop="requirementName" min-width="460">
          <template #="{ row }">
            <p class="table-requirement-name" @click="handleRowClick(row.ID)">{{ row.requirementName }}</p>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createAt" width="120" align="center">
            <template #="{ row }">
                <span>{{ tableTimeDate(row.createAt) }}</span>
            </template>
        </el-table-column>
        <el-table-column label="预计上线时间" prop="onlineTime" width="120" align="center">
            <template #="{ row }">
                <span>{{ tableTimeDate(row.onlineTime) }}</span>
            </template>
        </el-table-column>
        <el-table-column
            label="审核状态"
            prop="itemRequirementIsEnter"
            width="120"
            align="center">
          <template #="{ row }">
            <span
              :style="{
                color: enterStatus(row.itemRequirementIsEnter).bgColor,
              }"
              >{{ enterStatus(row.itemRequirementIsEnter).content }}</span
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              :disabled="row.itemRequirementIsEnter == 2"
              @click="handleOpenDialog(row.ID)"
            >
              审核
            </el-button>
            <!-- 审核不通过，可查看原因，待审核为禁用状态 -->
            <el-button
              size="small"
              type="primary"
              :disabled="(row.itemRequirementIsEnter == 1 && row.itemRequirementReview.length == 0)"
              @click="handleReviewEnterMsg(row.ID)"
            >
              审核记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 审核需求弹窗 -->
    <el-dialog v-model="dialogReviewVisible" title="审核需求" width="1200" :close-on-click-modal="false" top="8vh">
      <el-form style="max-height: 650px;overflow: auto;padding-right: 5px;">
        <el-form-item>
          <CommonRequirementInfoVue :isRequirementID="isRequirementID" :clearData="clearData" :isComment="false"></CommonRequirementInfoVue>
        </el-form-item>
        <el-form-item label="【项目审核人】对【需求草稿】文档评分：">
          <el-input-number
              style="width: 100px;"
              min="0"
              max="100"
              controls-position="right"
              v-model="reViewContentNumber"
          />
          <span style="font-size: 10px;color: red;">（备注：审核文档是否符合要求；评分分值：1-100）</span>
        </el-form-item>
        <el-form-item label="【项目审核人】对【需求草稿】文档评语：">
          <el-input
            maxlength="200"
            placeholder="请输入对【需求草稿】文档评语..."
            show-word-limit
            type="textarea"
            v-model="requirementMsg"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleReview(2)">不通过</el-button>
          <el-button type="primary" @click="handleReview(3)"> 通过 </el-button>
        </div>
      </template>
    </el-dialog>

     <!-- 查看审核记录弹窗 -->
     <el-dialog style="width: 600px;" title="审核记录" :close-on-click-modal="false" v-model="dialogRecordVisible" @close="handleCloseDiglog">
      <el-timeline style="max-width: 560px; max-height: 500px; padding: 20px; overflow-y: auto;" v-loading="dialogloading">
        <el-timeline-item
          v-for="(record, index) in recordData"
          :key="index"
          :timestamp="`审核时间：${tableTimeDateMsg(record.reviewDate)}`"
          :color="record.isEnter == 1 ? '#F56C6C' : record.isEnter == 2 ? '#E6A23C' :  record.isEnter == 3 ? '#67C23A' : '#F56C6C'"
          placement="top"
        >
        <el-card>
          <div class="record-title">
            <p>
              <span style="font-weight: bold;">审核人：</span>
              <span>{{ record.reViewUserName }}</span>
            </p>
            <p>
              <span style="font-weight: bold;">审核结果：</span>
              <span :style="{ color: enterStatus(record.isEnter).bgColor}">{{ enterStatus(record.isEnter).content }}</span>
            </p>
            <p>
              <span style="font-weight: bold;">评分：</span>
              <span>{{ record.reViewContentNumber }}</span>
            </p>
          </div>
          <!-- 评语 -->
          <div>
            <span style="font-weight: bold;">&nbsp;&nbsp;评语：</span>
            {{ record.reViewContent }}
          </div>
          <!-- 需求草稿文档下载 -->
          <div class="info-file-box" v-if="record.worldUrl !== ''">
              <p class="info-content-title"><span style="font-weight: bold;">需求草稿：</span></p>
              <ul class="info-file-ul">
                  <li class="info-file-item" v-for="(item, index) in handleRecordFiles(record.worldUrl)" :key="index">
                    <el-icon :size="12"><Document /></el-icon>
                    <span style="font-size: 12px;">{{ item.fileName ? item.fileName : `未知.${item.type}` }}</span>
                    <el-icon class="info-file-icon" @click="handlePreviewDocument(item.url)"><View /></el-icon>
                    <el-icon class="info-file-icon" @click="handleDownloadFile(item, baseUrl)"><Download /></el-icon>
                  </li>
              </ul>
          </div>
        </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>

    <!-- 需求详情弹窗 -->
    <el-dialog style="width: 1200px;" :close-on-click-modal="false" v-model="dialogInfoVisible" @close="dialogInfoVisible = clearData = false"  @closed="dialogInfoVisible = clearData = false" top="8vh">
        <CommonRequirementInfoVue :isRequirementID="isRequirementID" :clearData="clearData" :isComment="true"></CommonRequirementInfoVue>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, } from "element-plus";
import { ElForm } from "element-plus";
import {
  PostReviewRequirementMsg,
  GetEnterRequirement,
  GetRequirementEnterMsg,
} from "@/api/newDemands/index";

import { tableTimeDate, enterStatus, tableTimeDateMsg, handleDownloadFile, handleFileName, openPreviewInNewWindow, } from "@/utils/utils";
import CommonRequirementInfoVue from "@/components/requirement/comomRequirementInfo.vue";

const loading = ref(false);
const dialogloading = ref(false);
const searchFormData = ref({
  projectTitle: "",
  time: [null, null],
});

const dialogReviewVisible = ref(false); //审核需求弹窗

const isRequirementID = ref<any>(null); //当前操作任务ID
const requirementMsg = ref(""); //审核评语
const reViewContentNumber = ref<any>(100);//审核评分
  const draftFiles = ref<any>([]);//该需求所有的需求草稿地址
const baseUrl = ref(import.meta.env.VITE_SERVE);//服务器地址

////   待审核数据区域数据   ////
const allReviewRequirement = ref<any>([]); //我创建的所有需求
const dialogInfoVisible = ref(false);//查看需求弹窗控件
const clearData = ref(false);//控制是否清空子组件数据
const dialogRecordVisible = ref(false);//控制查看审核记录弹窗控件
const recordData = ref<any>([]);//所有审核记录

// TODO 获取【我待审核的需求】数据
const getAllReviewRequirement = async () => {
  loading.value = true;

  const { data } = await GetEnterRequirement({
    projectTitle: searchFormData.value.projectTitle,
    beginTime:
      searchFormData.value.time === null ? null : searchFormData.value.time[0],
    endTime:
      searchFormData.value.time === null ? null : searchFormData.value.time[1],
  });

  if (data.code === 200 && data.data !== null) {
    const list = Array.isArray(data.data) ? data.data : [];
    allReviewRequirement.value = list.map((item: any) => {
      return {
        ID: item.id ?? item.ID,
        requirementCreateName: item.requirementCreateName ?? "",
        requirementName: item.requirementName ?? "",
        itemRequirementWorldDraft: item.itemRequirementWorldDraft ?? "",
        itemRequirementIsEnter: item.itemRequirementIsEnter,
        itemRequirementIsGetTest: item.itemRequirementIsGetTest ?? 0,
        requirementContent: item.requirementContent ?? "",
        createAt: item.createdAt ?? item.createAt,
        requirmentFatherStatus: item.requirmentFatherStatus ?? 0,
        onlineTime: item.onlineTime ?? null,
        requirementBossName: item.requirementBossName ?? "",
        itemRequirementReview: item.itemRequirementReview ?? [],
      };
    });

    ElMessage.success(data.msg);
    loading.value = false;
    return;
  } else if (data.data === null && data.code === 200) {
    ElMessage.error("权限不足，无需审核！");
    allReviewRequirement.value = [];
    loading.value = false;
    return;
  } else {
    ElMessage.error(data.msg);
    loading.value = false;
    return;
  }
};

// 查看需求
const handleRowClick = async (id: number) => {
  dialogInfoVisible.value = true;
  isRequirementID.value = id;
};


// TODO 开启审核需求弹窗
const handleOpenDialog = (id: number) => {
  isRequirementID.value = id;
  dialogReviewVisible.value = true;
};

// TODO 审核需求提交函数
const submitReview = async (val: any) => {
  const { data } = await PostReviewRequirementMsg({
    itemRequirementId: isRequirementID.value,
    reViewContent: requirementMsg.value.trim(),
    reViewContentNumber: reViewContentNumber.value,
    isEnter: val,
  });

  if (data.code === 200) {
    ElMessage.success(data.msg);
    clearData.value = true;
    dialogReviewVisible.value = false;
    requirementMsg.value = "";
    reViewContentNumber.value = 100;
    loading.value = true;
    await getAllReviewRequirement();
    loading.value = false;
    return;
  } else {
    ElMessage.error(data.msg);
    clearData.value = true;
    dialogReviewVisible.value = false;
    requirementMsg.value = "";
    reViewContentNumber.value = 100;
    isRequirementID.value = null;
    return;
  }
};

// TODO 查看审核不通过原因
const handleReviewEnterMsg = async (id: number) => {
  dialogRecordVisible.value = true;
  dialogloading.value = true;

  const { data } = await GetRequirementEnterMsg(id);

  if(data.code === 200) {
    recordData.value = data.data;
    dialogloading.value = false;
  } else {
    ElMessage.error(data.msg);
    dialogloading.value = false;
    return;
  }
};

// TODO 关闭【查看审核记录】弹窗
const handleCloseDiglog = () => {
  dialogRecordVisible.value = false;
  recordData.value = [];
};

// TODO 处理每次审核的需求草稿
const handleRecordFiles = (val: string) => {
  // 需求草稿地址
  if(val !== "") {
      draftFiles.value = val.split("|").map((url: string) => {
        return handleFileName(url);
      });
  }
  return draftFiles.value;
};


// TODO 预览文件
const handlePreviewDocument = (url: string) => {
  let file = handleFileName(url);
  if (file.url.includes('Img') || file.url.includes('.pdf') || file.url.includes('.txt') || file.url.includes('.png') || file.url.includes('.gif') || file.url.includes('.jpge')) {
    window.open(`${'http://192.168.0.91:19081' + url}`, '_blank');
    return;
  } else {
    openPreviewInNewWindow( url, file.fileName);
  }
};

// TODO 审核需求功能
const handleReview = async (val: any) => {
  // 不通过
  if(val === 2) {
    if(requirementMsg.value == "") {
      ElMessage.warning("必须填写评语");
      return;
    } else {
      ElMessage.success("校验通过");
      await submitReview(val);
    }
  } else if(val === 3) {
    // 审核通过
    if(reViewContentNumber.value === null || reViewContentNumber.value === 0 || requirementMsg.value == "") {
      ElMessage.warning("必须填写评语和评分");
      return;
    } else {
      ElMessage.success("校验通过");
      await submitReview(val);
    }
  };
};

onMounted(async () => {
  getAllReviewRequirement();
});
</script>

<style lang="scss" scoped>
.content-container {
  display: flex;
  flex-direction: column;
  // TODO 搜索区域
  .search-wrap {
    width: 100%;
    //height: 40px;
    margin-bottom: 10px;
    display: flex;
    justify-content: flex-start;
    .search-wrap-item {
      margin-right: 10px;
      margin-bottom: 0;
      min-width: 200px;
      font-weight: bold;
      font-size: 24px;
      font-family: Arial, Helvetica, sans-serif;
      color: #000;
    }
  }

    // TODO 数据区域
    .table-requirement-name:hover,
    .table-download:hover {
        color: #409EFF;
        cursor: pointer;
    }

    // TODO 查看审核记录弹窗
    .record-title {
    display: flex;
    flex-direction: row;
    padding: 5px 10px;
    margin-bottom: 10px;
    background-color: #f0f0f0;
    border-radius: 2px;
    p {
      margin-right: 20px;
    }

  }
  // 需求草稿
  .info-file-box {
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-direction: row;
    margin: 10px 0 0;
    .info-content-title {
        width: 100px;
        padding: 0 10px;
    }

    .info-file-ul {
        width: calc(100% - 70px);
        text-align: left;
        display: flex;
        flex-direction: column;
        .info-file-item {
            width: 100%;
            margin-right: 10px;
        }
        .info-file-icon {
          color: #2d8cf0;
          margin-left: 5px;
        }
    }
  }
}
.el-form-item {
  margin-bottom: 8px!important;
}
</style>
